/*
 * Copyright (c) 2024 坚果派
 * 
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_digital_timer_depo/models/alarm.dart';

class AlarmItem extends StatefulWidget {
  final Alarm alarm;
  final Function(Alarm) onToggle;
  final Function(Alarm) onDelete;
  final Function(Alarm) onEdit;

  const AlarmItem({
    Key? key,
    required this.alarm,
    required this.onToggle,
    required this.onDelete,
    required this.onEdit,
  }) : super(key: key);

  @override
  State<AlarmItem> createState() => _AlarmItemState();
}

class _AlarmItemState extends State<AlarmItem> {
  // 用于检测双击的变量
  int _tapCount = 0;
  Timer? _timer;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 处理不同的交互方式
  void _handleInteraction() {
    switch (widget.alarm.interactionType) {
      case AlarmInteractionType.tap:
        widget.onToggle(widget.alarm);
        break;
      case AlarmInteractionType.doubleTap:
        _tapCount++;
        if (_timer == null) {
          _timer = Timer(const Duration(milliseconds: 300), () {
            _tapCount = 0;
            _timer = null;
          });
        }
        if (_tapCount == 2) {
          _timer?.cancel();
          _timer = null;
          _tapCount = 0;
          widget.onToggle(widget.alarm);
        }
        break;
      case AlarmInteractionType.longPress:
        widget.onToggle(widget.alarm);
        break;
      case AlarmInteractionType.swipe:
        // 滑动逻辑在Dismissible中处理
        break;
    }
  }

  // 格式化时间显示
  String _formatTime(TimeOfDay time) {
    final hour = time.hour.toString().padLeft(2, '0');
    final minute = time.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  // 获取重复日期的文本描述
  String _getRepeatDaysText() {
    final days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final selectedDays = <String>[];

    for (int i = 0; i < widget.alarm.repeatDays.length; i++) {
      if (widget.alarm.repeatDays[i]) {
        selectedDays.add(days[i]);
      }
    }

    if (selectedDays.isEmpty) {
      return '不重复';
    } else if (selectedDays.length == 7) {
      return '每天';
    } else if (selectedDays.length == 5 &&
        widget.alarm.repeatDays[0] &&
        widget.alarm.repeatDays[1] &&
        widget.alarm.repeatDays[2] &&
        widget.alarm.repeatDays[3] &&
        widget.alarm.repeatDays[4]) {
      return '工作日';
    } else if (selectedDays.length == 2 &&
        widget.alarm.repeatDays[5] &&
        widget.alarm.repeatDays[6]) {
      return '周末';
    } else {
      return selectedDays.join(', ');
    }
  }

  @override
  Widget build(BuildContext context) {
    // 根据交互类型选择不同的包装组件
    Widget alarmContent = Card(
      elevation: 2.0,
      margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _formatTime(widget.alarm.time),
                    style: TextStyle(
                      fontSize: 32.0,
                      fontWeight: FontWeight.bold,
                      color:
                          widget.alarm.isEnabled ? Colors.black : Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 4.0),
                  if (widget.alarm.label.isNotEmpty)
                    Text(
                      widget.alarm.label,
                      style: TextStyle(
                        fontSize: 16.0,
                        color: widget.alarm.isEnabled
                            ? Colors.black87
                            : Colors.grey,
                      ),
                    ),
                  const SizedBox(height: 4.0),
                  Text(
                    _getRepeatDaysText(),
                    style: TextStyle(
                      fontSize: 14.0,
                      color:
                          widget.alarm.isEnabled ? Colors.black54 : Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 4.0),
                  Text(
                    '交互方式: ${widget.alarm.interactionType.toString().split('.').last}',
                    style: TextStyle(
                      fontSize: 12.0,
                      fontStyle: FontStyle.italic,
                      color:
                          widget.alarm.isEnabled ? Colors.black45 : Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            Switch(
              value: widget.alarm.isEnabled,
              onChanged: (value) {
                widget.onToggle(
                  widget.alarm.copyWith(isEnabled: value),
                );
              },
            ),
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: () => widget.onEdit(widget.alarm),
            ),
          ],
        ),
      ),
    );

    // 根据交互类型包装不同的交互组件
    switch (widget.alarm.interactionType) {
      case AlarmInteractionType.tap:
        return GestureDetector(
          onTap: _handleInteraction,
          child: alarmContent,
        );
      case AlarmInteractionType.doubleTap:
        return GestureDetector(
          onTap: () {
            _tapCount++;
            if (_tapCount == 1) {
              // 显示视觉反馈
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('再次点击以切换闹钟状态'),
                  duration: Duration(milliseconds: 300),
                ),
              );
              // 重置计时器
              _timer?.cancel();
              _timer = Timer(const Duration(milliseconds: 300), () {
                setState(() {
                  _tapCount = 0;
                });
              });
            } else if (_tapCount == 2) {
              _tapCount = 0;
              _timer?.cancel();
              widget.onToggle(widget.alarm);
            }
          },
          child: alarmContent,
        );
      case AlarmInteractionType.longPress:
        return GestureDetector(
          onLongPress: () => widget.onToggle(widget.alarm),
          child: alarmContent,
        );
      case AlarmInteractionType.swipe:
        return Dismissible(
          key: Key('alarm_${widget.alarm.id}'),
          direction: DismissDirection.horizontal,
          confirmDismiss: (direction) async {
            if (direction == DismissDirection.endToStart) {
              // 从右向左滑动删除
              widget.onDelete(widget.alarm);
              return true;
            } else {
              // 从左向右滑动切换状态
              widget.onToggle(
                widget.alarm.copyWith(isEnabled: !widget.alarm.isEnabled),
              );
              return false;
            }
          },
          background: Container(
            color: Colors.green,
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: const Icon(Icons.alarm_on, color: Colors.white),
          ),
          secondaryBackground: Container(
            color: Colors.red,
            alignment: Alignment.centerRight,
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: const Icon(Icons.delete, color: Colors.white),
          ),
          child: alarmContent,
        );
    }
  }
}
